package com.sugree.thairath.breakingnews;

import java.util.List;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcelable;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.util.Log;

import com.sugree.base.BreakingNewsUpdateService;
import com.sugree.util.entity.Message;

public class BreakingNewsList extends Activity {
	private static final String TAG = "BreakingNewsList";

	private static final int MSG_CHANGED = 1;
	private static final int MSG_NOT_CHANGED = 2;

	private IBreakingNewsService mService;
	private ListView mList;
	private ProgressBar mProgressBar;
	private Button mRefresh;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);

		mList = (ListView)findViewById(R.id.list);
		mProgressBar = (ProgressBar)findViewById(R.id.progressbar);
		mRefresh = (Button)findViewById(R.id.button_refresh);

		mList.setItemsCanFocus(true);
		mList.setOnItemClickListener(mOnItemClickListener);

		mRefresh.setOnClickListener(mOnRefresh);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "start");
		NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		nm.cancelAll();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "resume");
		bindService(new Intent(this, BreakingNewsService.class), mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "pause");
		unbindService(mConnection);
		stopService(new Intent(this, BreakingNewsService.class));
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Log.d(TAG, "restore");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d(TAG, "save");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		getMenuInflater().inflate(R.menu.list, menu);

		Intent intent = new Intent(null, getIntent().getData());
		intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
		menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, BreakingNewsList.class), null, intent, 0, null);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.preferences:
			startActivity(new Intent(this, BreakingNewsPreference.class));
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void refresh() {
		mProgressBar.setVisibility(View.VISIBLE);
		startService(new Intent(this, BreakingNewsService.class));
	}

	protected void fillList() {
		List<Message> items;
		try {
			items = mService.getItems();
		} catch (RemoteException e) {
			Log.e(TAG, "getItems() "+e.toString());
			return;
		}
		if (items == null || items.isEmpty()) {
			refresh();
			return;
		}
		Log.d(TAG, items.toString());
		mList.setAdapter(new ArrayAdapter<Message>(this, R.layout.list_row, items) {
			@Override
			public View getView(int pos, View view, ViewGroup parent) {
				if (view == null) {
					view = getLayoutInflater().inflate(R.layout.list_row, null);
				}
				Message m = getItem(pos);
				view.setTag(m);

				TextView title = (TextView)view.findViewById(R.id.title);
				TextView author = (TextView)view.findViewById(R.id.author);

				title.setText(m.getTitle());
				author.setText(m.getAuthor());

				return view;
			}
		});
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			Log.d(TAG, "handleMessage "+msg.what);
			switch (msg.what) {
				case MSG_CHANGED:
					mProgressBar.setVisibility(View.GONE);
					fillList();
					break;

				case MSG_NOT_CHANGED:
					mProgressBar.setVisibility(View.GONE);
					break;

				default:
					super.handleMessage(msg);
			}
		}
	};

	private IBreakingNewsServiceCallback mCallback = new IBreakingNewsServiceCallback.Stub() {
		public void valueChanged(boolean changed) {
			Log.d(TAG, "valueChanged");
			if (changed) {
				mHandler.sendEmptyMessage(MSG_CHANGED);
			} else {
				mHandler.sendEmptyMessage(MSG_NOT_CHANGED);
			}
		}
	};

	private AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
			Intent intent = new Intent(BreakingNewsList.this, BreakingNewsItem.class);
			Message m = (Message)view.getTag();
			intent.putExtra("item", (Parcelable)m);
			startActivity(intent);
		}
	};

	private View.OnClickListener mOnRefresh = new View.OnClickListener() {
		public void onClick(View v) {
			refresh();
		}
	};

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mService = IBreakingNewsService.Stub.asInterface(service);
			fillList();
			try {
				mService.registerCallback(mCallback);
			} catch (RemoteException e) {
				Log.e(TAG, e.toString());
			}
		}

		public void onServiceDisconnected(ComponentName className) {
			try {
				mService.unregisterCallback(mCallback);
			} catch (RemoteException e) {
				Log.e(TAG, e.toString());
			}
			mService = null;
		}
	};
}
